<?php
namespace app\spadmin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use app\common\model\User;
use app\common\model\WechatUser;
use EasyWeChat\Factory;
use think\Log;
use think\Db;

class UserJoin extends Command
{
     protected function configure()
    {
        $this->setName('userjoin')->setDescription('mass user join wechat user ');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->joinUser();
        $this->invNum();
    }
    /**
     * 关联用户
     */
    protected function joinUser (){
        $user = User::all(['is_old'=>1]);
        if($user){
            foreach ($user as $key => $value) {
                Log::write('JOINUSER-list:userId='.$value['id']);
                $this->checkUser($value['id']);
            }
        }
    }

    
    /**
     * 更新分享数
     */
    protected function invNum(){
        User::chunk(100,function($users){
            foreach ($users as $user) {
                $user->inv_num = Db::name('User')->where('pid',$user->id)->count();
                $user->save();
            }

        });
    }
    /***
     * 验证用户
     */
    protected function checkUser($id){
        $wechatUser = WechatUser::get(['join_user_id'=>$id]);
        Log::write('JOINUSER-wechatUser:Id='.$wechatUser['id']?:0);
        if($wechatUser){
            Log::write('JOINUSER-wechatUser:Pid='.$wechatUser['pid']?:0);
            if($wechatUser['pid']>0){
                $pWechat = WechatUser::get(['id'=>$wechatUser['pid']]);
                if($pWechat && $pWechat['join_user_id']>0){
                    if($pWechat['pid']>0){
                        $tWechat = WechatUser::get(['id'=>$pWechat['pid']]);
                        if( $tWechat && $tWechat['join_user_id']>0){
                            
                            User::where('id',$id)->update(['is_old'=>0,'pid'=>$pWechat['join_user_id'],'tid'=>$tWechat['join_user_id']]);
                        }
                    }else{
                        
                        User::where('id',$id)->update(['is_old'=>0,'pid'=>$pWechat['join_user_id'],'tid'=>0]);
                    }
                    User::where('pid',$id)->update(['tid'=>$pWechat['join_user_id']]);
                }
            }else{
                
                User::where('id',$id)->update(['is_old'=>0]);
            }
        }
        
    }
}